<template>
    <div>
        <div class="tree-header">
            <h3 class="dict-title">
                {{ title }}
                <!-- (!isEdit && this.title != '字典分类目录') || this.select =='按目录' -->
                <el-button
                    type="primary"
                    size="mini"
                    class="fr minibtn"
                    v-if="
                        !isEdit &&
                            (this.title != '字典分类目录' ||
                                this.select == '按目录')
                    "
                    @click="isEdit = true"
                    >编辑</el-button
                >
                <el-button
                    size="mini"
                    class="fr minibtn"
                    v-else-if="!itemEdit && isEdit"
                    @click="handleClose"
                    >关闭</el-button
                >
                <!--<el-button type="primary" size="mini" class="fr mr10 minibtn" v-if="!isEdit" @click="importHandle">导入</el-button>-->
                <el-upload
                    class="fr"
                    :action="action"
                    accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :on-change="importHandle"
                >
                    <el-button
                        type="primary"
                        size="mini"
                        class="fr mr10 minibtn"
                        v-if="!isEdit"
                        >导入</el-button
                    >
                </el-upload>
            </h3>
            <el-input
                placeholder="输入编码名称进行查询"
                class="input-with-select"
                v-model="keyword"
                clearable
                @clear="typeChange"
            >
                <el-select
                    v-model="select"
                    slot="prepend"
                    placeholder="请选择"
                    @change="typeChange"
                    class="dict-search-select"
                >
                    <el-option
                        v-for="(item, index) in searchData"
                        :key="index"
                        :label="item.label"
                        :value="item.label"
                    ></el-option>
                </el-select>
                <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="treeSearch"
                ></el-button>
            </el-input>
        </div>

        <div
            :class="
                isEdit || isEdit2
                    ? 'tree-content mytree  mytree2'
                    : 'tree-content mytree'
            "
            v-loading="loading || treeLoading"
        >
            <div style="min-width: 100%; display: -webkit-inline-box">
                <el-tree
                    :data="data"
                    node-key="id"
                    default-expand-all
                    :filter-node-method="filterNode"
                    ref="tree"
                    :highlight-current="true"
                    :expand-on-click-node="false"
                    v-show="
                        this.title != '字典分类目录' || this.select == '按目录'
                    "
                    @node-click="nodeClick"
                    :props="{ children: 'childrens' }"
                    :indent="0"
                    :draggable="this.title == '字典分类目录'"
                    @node-drop="nodeDropHandle"
                    :allow-drop="allowDrop"
                >
                    <div class="custom-tree-node" slot-scope="{ node, data }">
                        <!--style="display:inline-block;width:24px;"-->
                        <span
                            v-if="
                                data.childrens &&
                                    data.childrens.length == 0 &&
                                    data.level < deep - 1 &&
                                    editId !== data[keyId]
                            "
                        ></span>
                        <span v-if="editId !== data[keyId]" class="tree-name">{{
                            data.name
                        }}</span>
                        <template v-else>
                            <el-input
                                class="tree-input"
                                v-model="data.name"
                                size="mini"
                                placeholder="请输入名称"
                                style="width: 70%"
                                :ref="'input' + data.id"
                            ></el-input>
                            <svg-icon
                                icon-class="yes-sl"
                                style="
                  color: #268ef9;
                  vertical-align: middle;
                  margin-left: 6px;
                  font-size: 22px;
                "
                                @click="finish(data)"
                                >ok</svg-icon
                            >
                            <svg-icon
                                icon-class="no-sl"
                                style="vertical-align: middle; font-size: 22px"
                                @click="cancel"
                            ></svg-icon>
                        </template>
                        <span
                            v-if="isEdit && editId !== data[keyId] && !itemEdit"
                            style="
                vertical-align: middle;
                font-size: 18px;
                padding-left: 10px;
              "
                        >
                            <svg-icon
                                icon-class="tree-edit"
                                style="color: #268ef9; margin-right: 6px"
                                v-if="data.id != 'root'"
                                @click="edit(data)"
                            >
                            </svg-icon>
                            <svg-icon
                                icon-class="tree-plus"
                                style="color: #268ef9; margin-right: 6px"
                                @click="append(data)"
                            >
                            </svg-icon>
                            <el-popconfirm
                                title="确认删除吗？"
                                @confirm="remove(data)"
                                v-if="data.id != 'root'"
                            >
                                <svg-icon
                                    icon-class="tree-minus"
                                    style="color: #ff414a"
                                    slot="reference"
                                >
                                </svg-icon>
                            </el-popconfirm>
                        </span>
                    </div>
                </el-tree>
                <div v-show="select == '按字段名'" style="width: 100%">
                    <div
                        class="table-item"
                        v-for="(item, index) in fieldList"
                        :key="index"
                        @click="handlebtableNodeClick(item)"
                    >
                        <div
                            :class="[
                                'table-item-top',
                                item.name.length > 30 ? 'narrowSize' : ''
                            ]"
                        >
                            {{ item.name }}
                        </div>
                        <div class="table-item-bottom">
                            {{ item.aliasName }}
                        </div>
                    </div>
                </div>
            </div>
            <div
                class="not-data"
                v-show="
                    (fieldList ? fieldList.length == 0 : false) &&
                        this.select == '按字段名'
                "
            >
                暂无数据
            </div>
        </div>
    </div>
</template>

<script>
import {
    editStandardTree,
    removeStandardTree
} from "@/api/dataManagement/standard/index";
export default {
    props: [
        "data",
        "title",
        "keyId",
        "type",
        "loading",
        "isEdit2",
        "searchData",
        "fieldList"
    ],
    data() {
        return {
            isEdit: false, //树状结构编辑状态
            itemEdit: false, //单项编辑中
            editId: "", //编辑项的id
            keyword: "", //搜索关键字
            treeLoading: false,
            deep: 0,
            select: "按目录",
            sort: 0,
            fileList: [
                {
                    name: "food.jpeg",
                    url:
                        "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
                },
                {
                    name: "food2.jpeg",
                    url:
                        "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
                }
            ],
            fileName: "",
            file: "",
            action: "/system/tree/importExcel/" + this.type + 1
        };
    },
    mounted() {
        console.log(this.type);
    },
    methods: {
        // 新增
        append(data) {
            const newChild = {
                id: Math.ceil(Math.random() * 1000000),
                name: "",
                level: data.level + 1,
                parentId: data.id == "root" ? "" : data.id,
                type: data.type,
                childType: 0,
                isAdd: true
            };
            data.childrens.push(newChild);
            this.edit(newChild);
        },
        // 编辑
        edit(data) {
            this.itemEdit = true;
            this.editId = data[this.keyId];
            // 编辑时自动聚焦
            this.$nextTick(() => {
                this.$refs["input" + data.id].focus();
            });
        },
        getParentData(data, id) {
            var sort = 0;
            for (var i = 0; i < data.length; i++) {
                if (data[i].id == id) {
                    this.sort = data[i].childrens.length;
                    return;
                } else {
                    data[i].childrens.length
                        ? this.getParentData(data[i].childrens, id)
                        : [];
                }
            }
        },
        // 新增、编辑保存
        finish(data) {
            if (data.name == "") {
                this.$message.error("不能为空");
                return false;
            }
            if (data.level != 0) {
                this.getParentData(this.data, data.parentId);
            }
            let param = {
                childType: 0,
                id: data.id,
                level: data.level,
                name: data.name,
                parentId: data.parentId,
                type: data.type,
                sort: data.sort == 0 || !data.sort ? this.sort : data.sort
            };
            if (data.isAdd) {
                delete param.id;
            }
            this.treeLoading = true;
            editStandardTree(param)
                .then(res => {
                    if (res.code == 200) {
                        this.itemEdit = false;
                        this.editId = "";
                    }
                    if (data.id == this.$route.query.id) {
                        this.$emit("ok", 1);
                    } else {
                        this.$emit("ok");
                    }
                    this.treeLoading = false;
                })
                .catch(err => {
                    this.treeLoading = false;
                });
        },
        // 删除
        remove(data) {
            this.treeLoading = true;
            removeStandardTree({ id: data.id })
                .then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: "删除成功",
                            type: "success"
                        });
                        if (data.id == this.$route.query.id) {
                            this.$router.push({ query: {} });
                            this.$emit("remove");
                        }
                    } else {
                        this.$message.error(res.message);
                    }
                    this.treeLoading = false;
                    this.$emit("ok");
                })
                .catch(err => {
                    this.treeLoading = false;
                    this.$message.error(res.message);
                });
        },
        // 点击搜索
        treeSearch() {
            if (this.select != "按目录") {
                this.$emit("filterHandle", this.keyword);
            } else {
                this.$refs.tree.filter(this.keyword);
            }
        },
        typeChange() {
            // console.log(this.data)
            this.keyword = "";
            this.$emit("reloadHandle", this.select);
        },
        // 树形节点筛选事件
        filterNode(value, data, node) {
            return this.checkBelongToChooseNode(value, data, node);
        },
        // 判断传入的节点是不是选中节点的子节点
        checkBelongToChooseNode(value, data, node) {
            let label = "name"; //指定为name
            if (data[label].indexOf(value) !== -1) {
                return true;
            }
            const level = node.level;
            // 如果传入的节点本身就是一级节点就不用校验了
            if (level === 1) {
                return false;
            }
            // 先取当前节点的父节点
            let parentData = node.parent;
            // 遍历当前节点的父节点
            let index = 0;
            while (index < level - 1) {
                // 如果匹配到直接返回
                if (parentData.data[label].indexOf(value) != -1) {
                    return true;
                }
                // 否则的话再往上一层做匹配
                parentData = parentData.parent;
                index++;
            }
            // 没匹配到返回false
            return false;
        },
        // 节点选中事件，供右侧联动使用
        nodeClick(data, node, obj) {
            if (this.isEdit) {
                return false;
            }
            this.$emit("nodeClick", data);
        },
        setHeightLight() {
            if (this.$route.query.id) {
                this.$nextTick(() => {
                    this.$refs.tree.setCurrentKey(this.$route.query.id);
                });
            } else {
                this.$refs.tree.setCurrentKey(null);
            }
        },
        // 返回当前选中节点的数据
        getCurrentNode() {
            return this.$refs.tree.getCurrentNode();
        },
        // 关闭编辑状态
        handleClose() {
            this.isEdit = false;
            this.setHeightLight();
        },
        beforeUpload(file) {
            this.files = file;
            //  const extension = file.name.split('.')[1] === 'xls'
            //  const extension2 = file.name.split('.')[1] === 'xlsx'
            //  const isLt2M = file.size / 1024 / 1024 < 5
            //  if (!extension && !extension2) {
            //   this.$message.warning('上传模板只能是 xls、xlsx格式!')
            //   return
            //  }
            //  if (!isLt2M) {
            //   this.$message.warning('上传模板大小不能超过 5MB!')
            //   return
            //  }
            this.fileName = file.name;
            return false; // 返回false不会自动上传
        },
        importHandle(file, fileList) {
            this.files = file.raw;
            this.fileName = file.name;
            var fileFormData = new FormData();
            fileFormData.append("fileExcel ", this.files, this.fileName);
            this.$emit("importHandle", fileFormData);
        },
        getMaxFloor(treeData) {
            let deep = 0;
            function eachData(data, index) {
                try {
                    data.forEach(elem => {
                        if (index > deep) {
                            deep = index;
                        }
                        if (elem.childrens.length > 0) {
                            eachData(elem.childrens, deep + 1);
                            throw new Error("end");
                        }
                    });
                } catch (err) {}
            }
            eachData(treeData, 1);
            this.deep = deep;
        },
        // 取消编辑
        cancel() {
            this.itemEdit = false;
            this.editId = "";
            this.$emit("ok");
        },
        nodeDropHandle(node, lastNode, type, e) {
            if (this.title == "字典分类目录") {
                // console.log(node,lastNode,item,e)
                this.$emit("nodeDropHandle", { node, lastNode, type, e });
            }
        },
        handlebtableNodeClick(item) {
            this.$emit("handleItem", item);
        },
        allowDrop(draggingNode, dropNode, type) {
            return dropNode.data.id != "root";
        }
    }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/system/tree.scss";
::v-deep
    .el-tree-node.is-expanded.is-focusable.is-drop-inner
    > .el-tree-node__content {
    background: #71b4f7;
}
.tree-header {
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
    .dict-title {
        border-left: 4px solid #1364b4;
        padding-left: 10px;
        line-height: 26px;
        height: 26px;
        font-weight: 400;
        font-size: 18px;
        margin: 0 0 14px 0;
        color: #606266;
        .edit-icon {
            margin-right: 6px;
            vertical-align: middle;
            font-size: 20px;
            margin-left: 14px;
            color: #5a5a5a;
            cursor: pointer;
        }
        .minibtn {
            height: 26px;
            padding: 0 16px;
            font-size: 14px;
        }
        .mr10 {
            margin-right: 10px;
        }
    }
    .el-input {
        ::v-deep.el-input__inner {
            border: 1px solid #b4b4b4;
            border-right: 0;
        }
        ::v-deep.el-input-group__append {
            background: #ffffff;
            border-color: #b4b4b4;
            position: relative;
            &::before {
                content: "";
                width: 1px;
                height: 20px;
                background: #969696;
                position: absolute;
                top: 6px;
                left: 0px;
            }
        }
    }
    .dict-search-select {
        ::v-deep .el-input__inner {
            background: #ffffff;
            width: 99px;
            line-height: 30px;
            border-top-left-radius: 4px;
            border-bottom-left-radius: 4px;
            border-color: #b4b4b4;
        }
        ::v-deep .el-input--suffix {
            .el-input__inner {
                background: #ffffff;
                width: 99px;
                line-height: 30px;
                border-top-left-radius: 4px;
                border-bottom-left-radius: 4px;
                border: 1px solid #b4b4b4;
                border-right: none;
            }
        }
    }
}
.tree-content {
    padding: 14px 0px;
    .tree-name {
        font-size: 14px;
        // font-weight: 400;
        color: #606266;
        line-height: 28px;
    }
}
::v-deep.el-tree {
    .el-tree-node__content {
        height: 28 px;
    }
}
::v-deep.el-tree--highlight-current {
    width: 100%;
}
::v-deep.el-input--mini .el-input__inner {
    height: 26px;
    line-height: 26px;
    font-size: 16px;
}
.mytree2
    ::v-deep
    .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: #ffffff;
}
.mytree {
    overflow: auto;
    height: 684px;
}

/**展示字段**/
.table-item {
    border-bottom: 1px solid #ddd;
    color: #606266;
    &:hover {
        cursor: pointer;
        background-color: #f5f7fa;
    }
    .table-item-top {
        font-size: 16px;
        font-weight: bold;
        padding-left: 10px;
        margin-top: 10px;
    }
    .narrowSize {
        font-size: 14px;
    }
    .table-item-bottom {
        padding: 10px 0;
        font-size: 12px;
        padding-left: 10px;
    }
}
.not-data {
    width: 100%;
    font-size: 14px;
    color: #909399;
    text-align: center;
    line-height: 27px;
}
</style>
